//
//  SearchListController.m
//  Mango
//
//  Created by lanou3g on 16/5/13.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "SearchListController.h"
#import "LeftModel.h"
#import "LeftModelCell.h"
#import "DetailViewController.h"
#import "searchStarCell.h"
#import "StarInfoModel.h"
#import "StarInfoViewController.h"
#define searchList_url @"http://api.app.happyjuzi.com/search/list/article"
@interface SearchListController ()
@property (nonatomic, strong) NSMutableArray *searchResult;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL isStar;
@property (nonatomic, strong) StarInfoModel *starModel;//明星模型
@property (nonatomic, copy) NSString *currentSkinModel;//夜间模式
@end

@implementation SearchListController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.rowHeight = 110;
    self.navigationItem.title = self.keyword;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.isStar = NO;//默认为no;
     self.searchResult = [NSMutableArray new];//搜索结果
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"LeftModelCell" bundle:nil] forCellReuseIdentifier:@"LeftModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"searchStarCell" bundle:nil] forCellReuseIdentifier:@"searchStarCell"];
    [self refreshData];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --private Method--更新皮肤模式 接到模式切换的通知后会调用此方法
-(void)updateSkinModel {
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//夜间模式
        self.tableView.backgroundColor = [UIColor blackColor];
    } else {//日间模式
//        self.tableView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.7];
    }
    [self.tableView reloadData];
}


//添加刷新
- (void)refreshData {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        self.tableView.mj_header.automaticallyChangeAlpha = YES;
        [self.tableView.mj_header beginRefreshing];
        
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

//请求网络数据
- (void)loadDataFromServerWithPage:(NSInteger)page {
    NSDictionary *parmar = @{@"uid":@"3971092394255935",@"res":@"1080x1920",@"ver":@"2.11",@"pf":@"android",@"channel":@"yingyongbao",@"accesstoken":@"e43c576b3de11eeeb758223cb56752c1",@"page":@(page),@"keyword":self.keyword,@"net":@"wifi",@"mac":@"",@"ts":@"0"};
    [[AFHTTPSessionManager manager]GET:searchList_url parameters:parmar progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (page == 1) {
            [self.searchResult removeAllObjects];
        }
        
        [self parserSearchResultWithDict:responseObject];//解析搜索结果
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

//解析搜索结果
- (void)parserSearchResultWithDict:(NSDictionary *)responseObject {
    NSDictionary *dataDict = responseObject[@"data"];
    //判断是否是明星
    NSArray *keys = dataDict.allKeys;
    if ([keys containsObject:@"star"]) {
        self.isStar = YES;
        NSDictionary *starDict = dataDict[@"star"][0];
        self.starModel = [StarInfoModel new];
        [self.starModel setValuesForKeysWithDictionary:starDict];
    }
    
    
    for (NSDictionary *dict in dataDict[@"list"]) {
        LeftModel *model = [LeftModel new];
        [model setValuesForKeysWithDictionary:dict];
        [self.searchResult addObject:model];
    }
}

//获取新数据
- (void)loadNewData {
    self.page = 1;
    [self loadDataFromServerWithPage:self.page];
}
//加载更多数据
- (void)loadMoreData {
    self.page++;
    [self loadDataFromServerWithPage:self.page];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    if (self.isStar) {
        return self.searchResult.count + 1;
    }else {
        return self.searchResult.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isStar) {
        if (indexPath.row == 0) {
            searchStarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchStarCell"];
            cell.model = self.starModel;
#pragma mark --private Method--更新皮肤模式
            if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
                [cell updateToNightSkinMode];
            }else {
                [cell updateToDaySkinMode];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else {
            LeftModelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeftModel"];
            cell.model = self.searchResult[indexPath.row - 1];
#pragma mark --private Method--更新皮肤模式
            if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
                [cell updateToNightSkinMode];
            }else {
                [cell updateToDaySkinMode];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }else {
        LeftModelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeftModel"];
        cell.model = self.searchResult[indexPath.row];
#pragma mark --private Method--更新皮肤模式
        if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {//日间模式
            [cell updateToNightSkinMode];
        }else {
            [cell updateToDaySkinMode];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isStar) {
        if (indexPath.row == 0) {
            StarInfoViewController *starInfoVC = [[StarInfoViewController alloc]init];
            starInfoVC.sid = self.starModel.ID;
            [self.navigationController pushViewController:starInfoVC animated:YES];
        }else {
            LeftModel *model = self.searchResult[indexPath.row - 1];
            DetailViewController *detailVC = [[DetailViewController alloc]init];
            detailVC.ID = model.ID;
             detailVC.listmodel = model;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }else {
        LeftModel *model = self.searchResult[indexPath.row];
        DetailViewController *detailVC = [[DetailViewController alloc]init];
        detailVC.ID = model.ID;
        detailVC.listmodel = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isStar) {
        if (indexPath.row == 0) {
            return 120;
        }else {
            return 110;
        }
    }else {
        return 110;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if (self.view.window == nil && [self isViewLoaded]) {
        self.view = nil;
    }
}
@end
